package com.xjnt.tvos.tvlibs.jsbridge.executor;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import org.json.JSONObject;

/**
 * Created by caoyong on 18-1-5.
 */

public class ScriptExecutor {

    private static final String JAVASCRIPT = "javascript:%s(%s);";


    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private WebView webView;
    private String callMethod = "";
    public ScriptExecutor(WebView webView) {
        this.webView = webView;
    }

    public void setCallMethod(String callMethod) {
        this.callMethod = callMethod;
    }

    public void invoke(String data) {
        final String execJs = String.format(JAVASCRIPT, this.callMethod, data);
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                    // 4.4 以下
                    webView.loadUrl(execJs);
                } else {
                    // 4.4 以上包含4.4
                    webView.evaluateJavascript(execJs, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                        }
                    });
                }
            }
        });
    }
}
